package cn.stylefeng.guns.modular.time.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.stylefeng.guns.modular.time.entity.Budget;
import cn.stylefeng.guns.modular.time.mapper.BudgetMapper;
import cn.stylefeng.guns.modular.time.model.request.BudgetRequest;
import cn.stylefeng.guns.modular.time.service.BudgetService;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class BudgetServiceImpl extends ServiceImpl<BudgetMapper, Budget> implements BudgetService {

    @Override
    public PageResult<Budget> findPage(BudgetRequest request) {
        LambdaQueryWrapper<Budget> qw = new LambdaQueryWrapper<>();
        qw.eq(Budget::getDelFlag, "N")
          .eq(Budget::getUserId, LoginContext.me().getLoginUser().getUserId())
          .orderByDesc(Budget::getStartDate);
        Page<Budget> page = this.page(new Page<>(request.getPageNo(), request.getPageSize()), qw);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public void add(BudgetRequest request) {
        Budget b = new Budget();
        b.setBudgetId(null);
        b.setUserId(LoginContext.me().getLoginUser().getUserId());
        b.setCategory(request.getCategory());
        b.setAmount(request.getAmount());
        b.setStartDate(request.getStartDate());
        b.setEndDate(request.getEndDate());
        b.setDelFlag("N");
        b.setCreateTime(new Date());
        this.save(b);
    }

    @Override
    public void edit(BudgetRequest request) {
        Budget b = this.getById(request.getBudgetId());
        if (b != null) {
            b.setCategory(request.getCategory());
            b.setAmount(request.getAmount());
            b.setStartDate(request.getStartDate());
            b.setEndDate(request.getEndDate());
            b.setUpdateTime(new Date());
            this.updateById(b);
        }
    }

    @Override
    public void delete(BudgetRequest request) {
        this.removeById(request.getBudgetId());
    }
}

